package com.lucker.service.user;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lucker.cds.mapper.CUserVirtualMoneyMapper;
import com.lucker.cds.model.CUserVirtualMoney;
import com.lucker.common.enums.VirtualMoneyHistoryType;
import com.lucker.common.enums.VirtualMoneyType;
import com.lucker.ds.model.UserVirtualMoney;
import com.lucker.ds.model.UserVirtualMoneyHistory;
import com.lucker.framework.exception.BaseServiceException;
import com.lucker.service.BaseServiceImpl;


@Service
public class UserVirtualMoneyServiceImpl extends BaseServiceImpl<UserVirtualMoney, CUserVirtualMoney, Long> implements UserVirtualMoneyService {
		
	
	@Autowired
	UserVirtualMoneyHistoryService userVirtualMoneyHistoryService;
	
	
	
	@Transactional
	public void addUserVirtualMoney(Long userId,Long money , VirtualMoneyType moneyType, VirtualMoneyHistoryType type,String businessId) {
		
		UserVirtualMoney _userVirtualMoney = new UserVirtualMoney();
		_userVirtualMoney.setUserId(userId);
		_userVirtualMoney.setUserVirtualMoneyType(moneyType.getCode());
		List<UserVirtualMoney> _list = queryAll(_userVirtualMoney);
		
		long beforMoney = 0;
		if(CollectionUtils.isEmpty(_list)) {
			if(money < 0) {
				throw new BaseServiceException("对不起,您的金币不够了！");
			}
			_userVirtualMoney.setUserVirtualMoneyAmount(money);
			add(_userVirtualMoney, false);
		}else {
			UserVirtualMoney _money = _list.get(0);
			beforMoney = _money.getUserVirtualMoneyAmount();
			_money.setUserVirtualMoneyAmount(beforMoney + money);
			if((beforMoney + money) < 0) {
				throw new BaseServiceException("对不起,您的金币不够了！");
			}
			
			modify(_money, false);			
		}
		
		
		
		//加虚拟币变化明细流水
		
		UserVirtualMoneyHistory _history = new UserVirtualMoneyHistory();
		_history.setUserId(userId.intValue());
		_history.setUserVirtualMoneyBeforAmount(beforMoney);
		_history.setUserVirtualMoneyChangeAmount(money);
		_history.setUserVirtualMoneyAfterAmount(beforMoney + money);
		if(money > 0) {
			_history.setUserVirtualMoneyChangeType(1L);
		}else {
			_history.setUserVirtualMoneyChangeType(0L);
		}
		
		_history.setUserVirtualMoneyChangeBusinessType(Long.valueOf(type.getCode()));
		_history.setUserVirtualMoneyChangeBusinessTypeName(type.getDesc());
		
		_history.setUserVirtualMoneyBusinessId(businessId);
		
		userVirtualMoneyHistoryService.add(_history, false);		
	}

	
	
	
	

	@Override
	public CUserVirtualMoneyMapper getCustomMapper() {
		return null;
	}

}
